﻿using ASmile.DBModel;
using ASmile.Extend;
using ASmile.ORM.Cores;

namespace ASmile.Com.Da
{
    public class RoleBLL : BLLCrudBase<Sys_Role>, IBLLCrud<Sys_Role>
    {
        public override ApiResult Del(Sys_Role role)
        {
            if (DB.QueryExist<Sys_RoleMenu>(s => s.RoleId == role.Id))
            {
                return RetErr("菜单中已经使用，请先移除角色中的菜单");
            }
            if (DB.QueryExist<Sys_RoleUser>(s => s.RoleId == role.Id))
            {
                return RetErr("用户中已经使用，请先移除角色中的用户");
            }
            return base.Del(role);
        }

        protected override void SetQuery(QueryCondition<Sys_Role> query, ArgPageData arg)
        {
            if (!arg.SearchVal.IsEmpty())
            {
                string likeStr = $"%{arg.SearchVal}%";
                query.WhereAnd(s => 
                    s.WEx_Like(s.RoleName, likeStr) ||
                    s.WEx_Like(s.RoleNamePY, likeStr));
            }
            query.OrderBy(s => s.AddTime);
        }

        protected override ApiResult<string> VerifyModel(Sys_Role model, bool isAdd)
        {
            if (model.RoleName.IsEmpty())
            {
                return RetErr(Sys_Role.CNRoleName, "角色名称不能为空");
            }
            if (DB.QueryExist<Sys_Role>(s => s.RoleName == model.RoleName && s.Id != model.Id))
            {
                return RetErr(Sys_Role.CNRoleName, "角色名称重复");
            }
            if (isAdd)
            {
                model.Id = NewId();
                return RetOK(model.Id, "新增成功");
            }
            else
            {
                return RetOK(string.Empty, "更新成功");
            }
        }
    }
}